<?php

namespace app\mini\controller;

use app\admin\model\Goods;
use app\company\model\CompanyGoodsRule;
use app\company\model\CompanyGoodsStore;
use app\company\model\CompanyOrderDetail;
use app\company\model\StoreSupplier;
use app\company\model\StoreUser;
use app\mini\model\Store;
use app\mini\validate\CompanyGoodsValidate;
use app\mini\model\CompanyGoods as CompanyGoodsModel;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\Response;

class CompanyGoods extends Base
{
    private CompanyGoodsModel $model;

    public function initialize()
    {
        parent::initialize();
        $this->model         = new CompanyGoodsModel();
        $this->validateClass = CompanyGoodsValidate::class;
    }

    /**
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list(): Response
    {
        $param = request()->param();
        validate($this->validateClass)->scene('list')->check($param);
        try {
            $store_ids[] = $this->userInfo->store_id;
            //如果是业务员,能获取所有门店的商品权限 TODO 该条件需要调整
            if ($this->userInfo->is_salesman == 1) {
                $store_ids = Store::where('salesman_id', $this->user_id)->column('id');
            }
            $supplier_ids = StoreSupplier::gs($this->company_id)->whereIn('store_id', $store_ids)->column('supplier_id');
            //查询门店所有商品
            $sql = (new CompanyOrderDetail())->alias('order')
                                             ->join('goods', 'goods.id = order.goods_id')
                                             ->join(['dt_company_goods' => 'company'], 'company.goods_id = order.goods_id')
                                             ->where('order.company_id', $this->company_id)
                                             ->where('company.status', 1)//控制商品上下架
                                             ->where('company.company_id', $this->company_id)//控制商品上下架
                                             ->whereIn('order.supplier_id', $supplier_ids);
            if ($name = request()->param('name', '')) {
                $sql = $sql->where('goods.name', 'like', '%' . $name . '%');
            }
            if ($goods_cate_id = request()->param('goods_cate_id', 0)) {
                $sql = $sql->where('goods.goods_cate_id', $goods_cate_id);
            }
            $sql   = $sql->field('order.goods_id')->group("order.goods_id");
            $count = $sql->count();
//            halt((new CompanyOrderDetail())->getLastSql());
            $list  = $sql->page($param['page'], $param['limit'])->order('order.goods_id')->select();
            foreach ($list as $key => $item) {
                $item->goods = Goods::where('id', $item->goods_id)->field('name,img,spec_type')->withTrashed()->find();
                $goods       = (new CompanyGoodsRule())->gs($this->company_id)->withTrashed()->where('goods_id', $item->goods_id)->order('money')->field('money,goods_rule_id')->find();//获取价格
                if (!$goods) {
                    unset($list[$key]);
                    continue;
                }
                $item->goods_rule_id = $goods->goods_rule_id;
                $item->price         = $goods->money;
                //销量 所有商品
                $item->sales = (int)redis()->zScore(xsGoodsKey() . $this->company_id, $item->goods_id);
            }
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success('获取成功', compact('list', 'count'));
    }


    /**
     * 获取多规格
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function rule(): Response
    {
        $param = Request::param();
        validate($this->validateClass)->scene('rule')->check($param);
        $sql       = new CompanyGoodsRule();
        $sql       = $sql->gs()->status()->withSearch('goods_id', $param);
        $goodsName = (new Goods())->where('id', $param['goods_id'])->value('name');
        $list      = $sql->field('id,goods_rule_id,money')->select()->each(function ($item) use ($goodsName) {
            $item->spec_name = $goodsName . $item->goodsRule()->withTrashed()->value('spec_name');
            $item->img       = $item->goodsRule()->withTrashed()->value('img');
            $item->stock     = (int)redis()->zScore(kcGoodsRuleKey() . $this->company_id, $item->goods_rule_id);//redis 中取库存 转换为INT类型
        });
        return $this->success('获取成功', compact('list'));
    }


    /**
     * 获取商品详情
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function detail(): Response
    {
        $goods_id = Request::param('goods_id');
        validate($this->validateClass)->scene('detail')->check(request()->param());
        $goods = $this->model->where('goods_id', $goods_id)->gs()->withTrashed()->find();
        if (!$goods) return $this->error('商品不存在');
        //获取商品信息
        $info                = Goods::where('id', $goods_id)->withTrashed()->field('id,name,img')->find();
        $info->descriptions  = $goods->descriptions;
        $rule                = (new CompanyGoodsRule())->gs()->where('goods_id', $goods_id)->order('money')->field('money,goods_id,goods_rule_id')->withTrashed()->find();//获取价格
        $info->goods_rule_id = $rule->goods_rule_id;
        $info->price         = $rule->money;
        $info->stock         = (int)redis()->zScore(kcGoodsKey() . $this->company_id, $goods_id);//redis 中取库存 转换为INT类型
        //销量 所有商品
        $info->sales = (int)redis()->zScore(xsGoodsKey() . $this->company_id, $rule->goods_id);
        return $this->success('获取成功', compact('info'));
    }


}